<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\commands;

use yii;
use yii\console\Controller;
use app\helpers\Curl;
use app\models\Huoke;
use yii\helpers\Json;

/**
 * This command echoes the first argument that you have entered.
 *
 * This command is provided as an example for you to learn how to create console commands.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class PushController extends Controller
{
    /**
     * This command echoes what you have entered as the message.
     * @param string $message the message to be echoed.
     */
    public function actionIndex($message = 'hello world')
    {
        $curl = new Curl();
        $huokes = Huoke::find();
        $huokes->where('approved=1');
        $huokes->andWhere('status=-1');
        $items = $huokes->all();

        foreach($items as $item)
        {
            //echo $item->id;
            $this->pushData($item);
        }
        //echo $this->getAccessToken();
    }

    public function pushData($huoke)
    {
        $url = Yii::$app->params['api']."/open/appsvr/channel/rsploan/unifyForTheCustomer.do";
        $params = array(
            'access_token'=>$this->getAccessToken(),
            'request_id'=>time()
        );
        $query =  http_build_query($params);
        $apiUrl = $url."?".$query;

//        $data = array(
//            'mediaSourceId'=>'ZTXYD-ZTDD-001',
//            'name'=>'张虎',
//            'teleNum'=>'18691508082',
//            'campaignCode'=>'XX_CAMP_1010WZ',
//            'campaignName'=>'1010直通网站',
//            'city'=>'上海市',
//            'isDirectForm'=>'N',
//            'pageType'=>'3',
//        );

        $data = array(
            'pageType'=>$huoke->pageType,
            'isDirectForm'=>$huoke->isDirectForm,
            'custSrc'=>$huoke->custSrc,
            'city'=>$huoke->city,
            'name'=>$huoke->name,
            'sex'=>$huoke->sex,
            'teleNum'=>$huoke->teleNum,
            'income'=>$huoke->income,
            'email'=>$huoke->email,
            'mediaSourceId'=>$huoke->mediaSourceId,
            'applyDate'=>$huoke->applyDate,
            'campaignCode'=>$huoke->campaignCode,
            'campaignName'=>$huoke->campaignName,
            'creditYears'=>$huoke->creditYears,
            'credit'=>$huoke->credit,
            'hasCreditCard'=>$huoke->hasCreditCard,
            'loanExperience'=>$huoke->loanExperience,
            'mortgage'=>$huoke->mortgage,
            'hasCarLoan'=>$huoke->hasCarLoan,
            'smsAccept'=>$huoke->smsAccept,
            'recommenderAccount'=>$huoke->recommenderAccount,
            'recommenderName'=>$huoke->recommenderName,
            'recommenderMobile'=>$huoke->recommenderMobile,
            'education'=>$huoke->education,
            'birthDate'=>$huoke->birthDate,
            'createSrc'=>$huoke->createSrc,
            'profession'=>$huoke->profession,
            'payoffType'=>$huoke->payoffType,
        );

        $curl = new Curl();
        $res = $curl->setOption(
            CURLOPT_POSTFIELDS,
            http_build_query($data))
            ->post($apiUrl);

        if($res)
        {
            $msg = $this->getJsonData($res);

            if($msg)
            {
                $json = Json::decode($msg);
            }
            else
            {
                $json = array();
            }

            if(isset($json['errorCode']) && $json['errorCode'])
            {
                $huoke->status = $json['errorCode'];
                $huoke->statusMessage = $json['errorMsg'];
                $huoke->save();
            }
            else
            {
                $huoke->status = 0;
                $huoke->statusMessage = '';
                $huoke->save();
            }
        }

    }

    public function getJsonData($json)
    {
        $pattern = '/"({.*?})"/';
        $match = null;
        preg_match($pattern,$json,$match);
        if($match && $match[1])
        {
            return $match[1];
        }
        return '';
    }

    public function resetAccessToken()
    {
        yii::$app->cache->delete('access_token');
    }

    public function getAccessToken()
    {
        $accessToken = yii::$app->cache->get('access_token');
        if($accessToken) return $accessToken;
        $url = Yii::$app->params['api']."/oauth/oauth2/access_token";
        $params = array(
            'client_id'=>Yii::$app->params['id'],
            'grant_type'=>'client_credentials',
            'client_secret'=>Yii::$app->params['secret']
        );
        $query =  http_build_query($params);

        $apiUrl = $url."?".$query;

        $curl = new Curl();
        $res = $curl->get($apiUrl);
        if($res)
        {
            $json = json_decode($res,true);
            if($json && isset($json['ret']) && $json['ret']==0)
            {
                $accessToken = $json['data']['access_token'];
                yii::$app->cache->set('access_token',$accessToken, $json['data']['expires_in']);
            }
        }
        return $accessToken;
    }
}
